package main

import (
	"fmt"
	"sync"
	"time"
)

func test1() {
	m := map[int]int{
		1: 11,
		2: 12,
		3: 13,
	}

	go func() {
		for i := 0; i < 1000; i++ {
			m[i] = i * i
		}
	}()

	go func() {
		for i := 0; i < 1000; i++ {
			fmt.Println(m[i])
		}
	}()

	time.Sleep(time.Second)
	//执行后报错:fatal error: concurrent map read and map write
}

func test2() {
	var m sync.Map

	go func() {
		for i := 0; i < 1000; i++ {
			m.Store(i, i*i)
		}
	}()

	go func() {
		for i := 0; i < 1000; i++ {
			data, _ := m.Load(i)
			fmt.Println(i, data)
		}
	}()

	time.Sleep(time.Second)
	//执行后正确输出
}

func main() {
	//test1()
	test2()
}
